import 'vux/src/styles/reset.less';
import './index.scss'
import {
  Swiper,
  Spinner,
  Scroller,
  Tab,
  TabItem,
  Sticky,
  Flexbox,
  FlexboxItem,
  ViewBox
} from 'vux'
import utils from 'js/utils.js'

import "../../modules/icon/fonts/iconfont.js";




import {
  hostImg
} from 'js/host-config'
import {
  fetch,
  rap
} from 'js/fetch.js'




let url = {
  getAD: 'api/ads',
  getCategories: 'api/book/categories',
  getBooks: 'api/books',
  getHomeRecommend: 'api/books?type=home_recommend',
  wechat_login: 'api/wechat/login'
}

url = rap(url)
import Myhead from 'components/head/head.vue'
// import Slide from 'components/slide/slide.vue'
import Top from 'components/top/top.vue'
// import Search from 'components/search/search.vue'
import Foot from 'components/foot/foot.vue'

import mixin from 'js/mixin.js'
import { cookie } from 'vux'


new Vue({
  el: '#body',
  data: {
    index: 1,
    ADList: [],
    categoriesList: [],
    listIndex: 0,
    transitionName: 'slide-left',
    isLogin: '',
    bookList: [],
    mylist: [], //临时存放
    demo4Value: {
      pullupStatus: 'default'
    },
    lists: [{
        title: '婴儿画报2017年第三季度合订本',
        img: '/static/book.jpg',
        author: '作者金波',
        status: '已领取',
      },
      {
        title: '婴儿画报2017年第三季度合订本',
        img: '/static/book.jpg',
        author: '作者金波',
        status: '已领取',
      },
      {
        title: '婴儿画报2017年第三季度合订本',
        img: '/static/book.jpg',
        author: '作者金波',
        status: '已领取',
      }
    ],
    limit: 6,
    offset: 0,
    demo4Value: {
      pullupStatus: 'default'
    },
    stop: false
  },
  created() {

    //console.log(cookie.get('token')==undefined)
    if (!!utils.getQuery('code')) {
      //拿到code 用code换token
      
      fetch('post', `${url.wechat_login}`, {
        code: utils.getQuery('code')
      }).then(res => {
        if (res.status >= 200 && res.status <= 500) {
            
          //console.log(res.data.status=false)
          //res.data.token=null;
          if(!!res.data.status){
            //已经注册了
            
            cookie.set('token', res.data.token)
            window.localStorage.setItem('openid',res.data.user.openid)

          }else{
            window.localStorage.setItem('openid',res.data.user.openid)

          }
          
          
          
        }
      })

    } else {
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx929c847291c42447&redirect_uri=${encodeURIComponent('https://www.5chelib.com')}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
    }
    //window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx929c847291c42447&redirect_uri=${encodeURIComponent('https://www.5chelib.com')}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`alert(window.location.href)
    

    //    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${options.appId}&redirect_uri=${encodeURIComponent(url)}&response_type=code&scope=${options.scope}&state=${options.state}#wechat_redirect`
    this.isLogin = utils.isLogin()
    this.getADList()
    this.getHomeRecommend()
    if (typeof (utils.getQuery('user_id')) != 'undefined') {
      window.localStorage.setItem('user_id', utils.getQuery('user_id'));
    }
    this.siteId = window.localStorage.getItem("siteID")
    this.siteName = window.localStorage.getItem("siteName")


  },
  mounted() {},
  methods: {
    change(index) {
      this.stop = false;
      this.limit = 6;
      this.offset = 0;
      this.bookList = []
      if (index == 1) {
        this.index = 1
        this.getHomeRecommend()
      } else if (index == 2) {
        this.index = 2
        this.getSiteList()
      } else {
        this.stop = true
      }

      //this.getHomeRecommend()
      //this.bookList=[]
    },
    getSiteList() {
      let _this = this;
      if (this.stop == true) {
        //没有数据就停止懒加载
        return
      }
      //获取站点图书
      fetch('get', `${url.getBooks}?limit=${this.limit}&offset=${this.offset}&site_id=${window.localStorage.getItem('siteID')}`).then(res => {
        if (res.status >= 200 && res.status <= 500) {
          if (res.data.length == 0) {
            this.stop = true
          }
          res.data.forEach((item, index) => {
            item.cover = `${hostImg}${item.cover}`
            this.bookList.push(item)

            //
            setTimeout(() => {
              _this.demo4Value.pullupStatus = 'default'
              _this.$nextTick(() => {
                _this.$refs.scroller.reset()
              })
            }, 0)


          })

        }
      })

    },
    load4() {

      if (this.index == 1) {

        this.demo4Value.pullupStatus = 'up'
        this.offset += this.limit
        //  this.offset += 0
        this.getHomeRecommend()

      } else if (this.index == 2) {
        this.demo4Value.pullupStatus = 'up'
        this.offset += this.limit
        //  this.offset += 0
        this.getSiteList()

      }




    },
    show(index) {
      //console.log(this.listIndex + 'listIndex')
      //console.log(index + 'index')
      if (this.listIndex > index) {
        this.transitionName = 'slide-right'
      } else if (this.listIndex > index) {
        this.transitionName = 'slide-left'
      }
      this.listIndex = index
    },
    getADList() {
      //获取首页广告列表 轮播图
      fetch('get', url.getAD).then(res => {
        if (res.status === 200) {
          res.data.forEach((item, index) => {
            let obj = {
              img: `${hostImg}${item.ad_image}`,
              //url: `${item.link}`,
              /*title: `${item.name}`*/
            }
            this.ADList.push(obj)
          })
        } else {

        }
      })
    },
    getHomeRecommend() {
      let _this = this;
      if (this.stop == true) {
        //没有数据就停止懒加载
        return
      }
      //获取首页推荐图书
      fetch('get', `${url.getHomeRecommend}&limit=${this.limit}&offset=${this.offset}`, {}).then(res => {
        if (res.status >= 200 && res.status <= 500) {
          if (res.data.length == 0) {
            this.stop = true
          }
          res.data.forEach((item, index) => {
            item.cover = `${hostImg}${item.cover}`
            this.bookList.push(item)

            //
            setTimeout(() => {
              _this.demo4Value.pullupStatus = 'default'
              _this.$nextTick(() => {
                _this.$refs.scroller.reset()
              })
            }, 0)


          })

        }
      })
    },
    getCategories() {
      //获取首页一级栏目
      let _this = this
      fetch('get', url.getCategories, {
        params: {
          pid: 0,
        }
      }).then(res => {
        if (res.status >= 200 && res.status <= 500) {
          this.categoriesList = res.data
          //console.log(res)
          res.data.forEach(function (item, index) {
            //console.log(item)
            //axios.all([this({ id: item.id }), getUserPermissions()])
            //  .then(axios.spread(function (acct, perms) {
            // Both requests are now complete
            //  }));
            _this.getbook({
              category_id: item.id
            })
          })
        }
      })
    },
    _getbook(config) {
      return fetch('get', url.getBooks, {
        params: config
      })
    },
    getbook(config = null) {
      //获取图书
      let _this = this
      fetch('get', url.getBooks, {
        params: config
      }).then(res => {
        //this.bookList.psuh(res.data)
        if (res.status >= 200 && res.status <= 500) {
          //this.categoriesList = res.data
          res.data.forEach((item, index) => {
            item.cover = `${hostImg}${item.cover}`
          })
          _this.mylist[config.category_id - 1] = res.data
          _this.$set(_this, 'bookList', _this.mylist);
        }

      })
    },
    goDetail(id) {
      window.location.href = `./books_detail.html?id=${id}`
    },
    goRegister() {
      //如果登录了就跳购买会员页面 没有就去注册
      if (this.isLogin) {
        window.location.href = './buy_member.html'
      } else {
        window.location.href = './register.html'
      }
    }
  },
  components: {
    Swiper,
    Scroller,
    Spinner,
    Tab,
    TabItem,
    Sticky,
    Flexbox,
    FlexboxItem,
    ViewBox
  },
  mixins: [mixin]
})
